// pages/plan_detail/plan_detail.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    read:false,
    content:"",
    checks:[],
    type:"",
    fankui: false,
    zid: "",
    f_id: "",
    contents: "",
    j_id: "",
  },
  big_img:function(e){
    var url=e.currentTarget.dataset.url;
    var urls=e.currentTarget.dataset.urls;
    wx.previewImage({
      current:url,
      urls: urls,
      
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id;
    var that = this;
    that.setData({
      id:id
    })
    if(options.type != undefined)
    {
      that.setData({
        type:options.type
      })
    }
    app.util.request({
      'url': 'entry/wxapp/hzbingli.url',
      success: function (res) {
        console.log(res)
        that.setData({
          url: res.data,
        })
      }
    })
    this.getDetail();
  },
  toask:function(){
    wx.navigateTo({
      url: '/hyb_yl/zhuanjiasubpages/pages/chat_list/chat_list?zid=' + this.data.info.zid + '&openid=' + wx.getStorageSync('openid') + '&role=0&title='+this.data.info.z_name,
    })
  },
  getDetail:function(res)
  {
    var that = this;
    app.util.request({
      'url':"entry/wxapp/follow.suifang_detail",
      data:{
        id:that.data.id
      },
      success:function(res)
      {
        that.setData({
          checks:res.data.checks,
          j_id:res.data.j_id,
          openid:res.data.openid,
          content:res.data.checks
        })
        
      }
    })
  },
  // 关心提醒 未读
  bindread(){
    this.setData({
      read:true
    })
  },
  // 患教详情
  hjdetail:function(e){
    var id = e.currentTarget.dataset.id;
    var f_id = e.currentTarget.dataset.f_id;
    var j_id = e.currentTarget.dataset.j_id;
    wx.navigateTo({
      url: '/hyb_yl/backstageLife/pages/particulars/particulars?h_id='+id+'&typs=suifang&f_id='+f_id+"&j_id="+j_id,
    })
  },
  answerdetail:function(e){
    var id = e.currentTarget.dataset.id;
    var f_id = e.currentTarget.dataset.f_id;
    var j_id = e.currentTarget.dataset.j_id;
    var type = this.data.type;
    wx.navigateTo({
      url: '/hyb_yl/huanzhe/pages/questionnaire/questionnaire?id='+id+'&typs=suifang&f_id='+f_id+"&j_id="+j_id+'&type='+type,
    })
  },
  // 随访反馈
  suifang: function (e) {
    var that = this;
    that.setData({
      fankui: true,
    })
  },
  // 随访反馈内容
  bindinputs(e) {
    this.setData({
      contents: e.detail.value
    })
  },
  // 确定
  queding() {
    var that = this
    
    app.util.request({
      'url': "entry/wxapp/follow.add_feedback",
      data: {
        openid: that.data.info.openid,
        zid: that.data.info.zid,
        f_id: that.data.info.id,
        content: that.data.contents,
        j_id: that.data.info.j_id,
      },
      success: function (res) {
        that.setData({
          fankui: false,
        })
        wx.showToast({
          title: '反馈成功',
          icon:"none"
        })
      }
    })

  },
  // 取消
  closezhe() {
    this.setData({
      fankui: false
    })
  },
  // 上传图片
  bindadds: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var checks = that.data.checks;
    var imglist = checks[index].imglist;
    wx.chooseImage({
      count: 9 - imglist.length, // 默认9
      success: function (res) {
        console.log(res)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        //上传图片
        var successUp = 0; //成功个数
        var failUp = 0; //失败个数
        var length = res.tempFilePaths.length; //总共个数

        var i = 0; //第几个
        that.uploadDIY(res.tempFilePaths, successUp, failUp, i, length,index);
      },
    });
  },
  uploadDIY(filePaths, successUp, failUp, i, length,indexs) {
    var that = this;
    wx.showLoading();
    var uniacid = app.siteInfo.uniacid;
    var checks = that.data.checks;
    var imglist = checks[indexs].imglist;
    console.log(indexs)
    console.log("1111"+imglist)
    wx.uploadFile({
      url: that.data.url + 'app/index.php?i=' + uniacid + '&c=entry&a=wxapp&do=Uploadback&m=hyb_yl',
      filePath: filePaths[i],
      name: 'upfile',
      formData: {},
      success: (resp) => {
        successUp++;
        imglist.push(resp.data);
        console.log("2222"+imglist)
        checks[indexs].imglist = imglist
        that.setData({
          checks: checks
        })
        console.log(checks)
      },
      fail: (res) => {
        failUp++;
      },
      complete: () => {
        i++;
        if (i == length) {
          wx.hideLoading();
        } else { //递归调用uploadDIY函数
          this.uploadDIY(filePaths, successUp, failUp, i, length,indexs);

        }
      },
    });
  },
  //图片删除
  binddel(e){
    // var t = this, ss = t.data.imglist,i=e.currentTarget.dataset.dex;
    // ss.splice(i,1);
    // t.setData({
    //   imglist:ss
    // })
  },
  // 请填写
  bindinput(e){
    var that = this;
    var value = e.detail.value
    var index = e.target.dataset.index
    var checks = that.data.checks;
    var min_value = checks[index].min_value;
    var max_value = checks[index].max_value;
    
    if(parseFloat(value) < parseFloat(min_value))
    {
      checks[index].status = 1;
    }else if(parseFloat(value) > parseFloat(max_value))
    {
      checks[index].status = 2;
    }else{
      checks[index].status = 0;
    }
    checks[index].value = value;
    console.log(checks);
    that.setData({
      checks:checks
    })
    console.log(that.data.checks)

  },
  changeinputs(e){
    var that = this;
    var value = e.detail.value
    var index = e.target.dataset.index
    var checks = that.data.checks;
    checks[index].value = value;
    that.setData({
      checks:checks
    })
  },
  // 结束随访计划
  over_follow:function(){
    var that = this;
    var id = that.data.id;
    app.util.request({
      'url':"entry/wxapp/follow.over_follow",
      data:{
        id:id
      },
      success:function(res)
      {
        wx.navigateBack({})
      }
    })
  },
  // 上传化验单
  bindup(e){
    wx.navigateTo({
      url: '/hyb_yl/huanzhe/pages/test_sheet/test_sheet?id='+this.data.id,
    })
  },
  onShow(){
    var that = this;
    app.util.request({
      'url':"entry/wxapp/follow.suifang_detail",
      data:{
        id:that.data.id
      },
      success:function(res)
      {
        that.setData({
          info:res.data
        })
        
      }
    })
  },
  // 提交随访
  bindsubmit(){
    var that = this;
    var id = that.data.id;
    var checks = that.data.checks;
    for(var i=0;i<checks.length;i++)
    {
      if(checks[i].is_upload == 1 && checks[i].imglist.length == 0)
      {
        wx.showToast({
          title: '请上传'+checks[i].title,
          icon:'none'
        })
        return;
      }else if(checks[i].is_upload == 0 && (checks[i].value == '' || checks[i].value == undefined))
      {
        wx.showToast({
          title: '请填写'+checks[i].title,
          icon:'none'
        })
        return;
      }
    }
    app.util.request({
      'url':"entry/wxapp/follow.add_follow",
      data:{
        j_id:that.data.info.j_id,
        checks:JSON.stringify(checks),
        id:that.data.info.id,
        openid:wx.getStorageSync('openid'),
        zid:that.data.info.zid
      },
      success:function(res)
      {
        wx.showToast({
          title: '提交成功',
        })
        wx.navigateBack({})
      }
    })
  },
  bindadd:function(e){
    var type = e.currentTarget.dataset.type;
    var title = e.currentTarget.dataset.title;
    var that = this;
    
    if(type == 'blood_pressure')
    {
      wx.showModal({
        title: '提示',
        content:"请使用血压仪测量，数据会自动上传,是否查看",
        success:function(con)
        {
          if(con.confirm)
          {
            wx.navigateTo({
              url: '/hyb_yl/zhuanjiasubpages/pages/huanzhexinxi/huanzhexinxi?type=equipment&link=/hyb_yl/zhuanjiasubpages/pages/bloodpressure_report/bloodpressure_report',
            })
          }
        }
      })
    }else if(type == 'blood_sugar' || type == 'uricacid' || type == 'heartrate')
    {
      wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
        success: function (res) {
          console.log(res)
          wx.showToast({
            title: '初始化成功',
            icon: 'success',
            duration: 800
          })
          that.findBlues();//2.0
        },
        fail: function (res) {//如果手机上的蓝牙没有打开，可以提醒用户
          console.log(333)
          wx.showModal({
            title: '提示',
            content: "手机蓝牙未开启，仅可查看记录",
            success: function (con) {
              if (con.confirm) {
                if(type == 'blood_sugar')
                {
                  var url = '/hyb_yl/zhuanjiasubpages/pages/bloodsugar_report/bloodsugar_report';
                }else if(type == 'uricacid')
                {
                  if(title.indexOf('尿酸') >=0)
                  {
                    var url = "/hyb_yl/pharmacy/pages/uric_acid/uric_acid";
                  }else if(title.indexOf('血糖')  >=0)
                  {
                    var url = '/hyb_yl/zhuanjiasubpages/pages/bloodsugar_report/bloodsugar_report';
                  }else if(title.indexOf('胆固醇')  >=0)
                  {
                    var url = '/hyb_yl/pharmacy/pages/cholesterol/cholesterol';
                  }
                  
                }else if(type == 'heartrate')
                {
                  var url = "/hyb_yl/pharmacy/pages/heart_rate_cont/heart_rate_cont";
                }
                that.setData({
                  url:url
                })
                wx.navigateTo({
                  url: url + '?j_id=' + that.data.info.j_id+'&openid='+that.data.info.openid,
                })
              }
            }
          })
        }
      })
    }else if(type == 'temperature')
    {
      wx.openBluetoothAdapter({
        success: function (res) {
          that.Search();
        },
        fail: function (res) {
          wx.showModal({
            title: '提示',
            content: "手机蓝牙未开启，仅可查看记录",
            success: function (con) {
              if (con.confirm) {
                wx.navigateTo({
                  url: '/hyb_yl/pharmacy/pages/temperature/temperature' + '?j_id=' + that.data.j_id,
                })
              }
            }
          })
        }
      })
    }
  },
  findBlues() {
    var that = this
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: function (res) {
        console.log(res);
        wx.showLoading({
          title: '正在搜索设备',
        })
        that.getBlue()//3.0
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  getBlue() {
    var that = this
    var url = that.data.url;
    var type = '';
    
    if (url == '/hyb_yl/pharmacy/pages/uric_acid/uric_acid') {
      type = 'UA';
    } else if (url == '/hyb_yl/pharmacy/pages/cholesterol/cholesterol') {
      type = 'CHOL';
    } else if (url == '/hyb_yl/zhuanjiasubpages/pages/bloodsugar_report/bloodsugar_report') {
      type = 'GLU';
    }
    wx.getBluetoothDevices({
      success: function (res) {
        console.log(res)
        wx.hideLoading();
        for (var i = 0; i < res.devices.length; i++) {
          //that.data.inputValue：表示的是需要连接的蓝牙设备ID，简单点来说就是我想要连接这个蓝牙设备，所以我去遍历我搜索到的蓝牙设备中是否有这个ID
          if (res.devices[i].name.indexOf('PM10') > -1 || res.devices[i].localName.indexOf('PM10') > -1 || res.devices[i].name.indexOf('Device') > -1 || res.devices[i].localName.indexOf('Device') > -1) {
            that.setData({
              deviceId: res.devices[i].deviceId,
              consoleLog: "设备：" + res.devices[i].deviceId,
            })
            
            wx.redirectTo({ url: '/hyb_yl/pharmacy/pages/thermometer/index?connectedDeviceId=' + res.devices[i].deviceId + '&name=' + res.devices[i].name + '&j_id=' + that.data.j_id + '&type=' + type });
            return;
          }
        }
      },
      fail: function () {
        console.log("搜索蓝牙设备失败")
      }
    })
  },
  // 蓝牙设备检测数据体温心电
  Search() {
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      success(res) {
        wx.showLoading({
          title: '正在搜索设备...',
        });

        var delayTimer = setInterval(function () {
          console.log('sousuo');
          that.findBlue();
        }, 2000);
        that.setData({
          delayTimer: delayTimer
        })
      },
      fail() {
        that.setData({
          showText: "搜索设备失败"
        })
        that.closeFindBlue();
      }
    })

  },
  findBlue() {
    var that = this;
    console.log('搜索开始')
    wx.getBluetoothDevices({
      success: function (res) {
        console.log('搜索成功')
        console.log(res)
        var deviceNum = 0;
        if (res.devices && (deviceNum = res.devices.length) >= 1) {
          that.setData({
            showText: "搜索设备数量：" + deviceNum
          })

          that.setData({
            devicesList: []

          });

          var biolandDevice;
          for (var i = 0; i < deviceNum; i++) {
            var device = res.devices[i];
            var deviceName = device.name;
            if (deviceName == null || deviceName == '')
              continue;

            var rssi = device.RSSI;
            if (deviceName.indexOf('Bioland-IT') > -1) {
              biolandDevice = device;
              var name = "devicesList[" + i + "].name";
              that.setData({
                [name]: deviceName
              });
              break;
            } else if (deviceName.indexOf('PM10') > -1) {
              biolandDevice = device;
              var name = "devicesList[" + i + "].name";
              that.setData({
                [name]: deviceName
              });
              break;
            } else if (deviceName.indexOf('BLE') > -1) {
              biolandDevice = device;
              var name = "devicesList[" + i + "].name";
              that.setData({
                [name]: deviceName
              });
              break;
            }
          }
          console.log(biolandDevice)
          if (biolandDevice != null) {
            wx.hideLoading();
            that.closeFindBlue();
            that.Connect(biolandDevice);
          }

        }
      }
    })
  },
  closeFindBlue() {
    var that = this;
    clearInterval(that.data.delayTimer);
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
      }
    })
  },
  Connect(data) {
    if (data == null)
      return;
    var that = this
    wx.showLoading({
      title: '连接设备中...',
    })
    wx.createBLEConnection({
      deviceId: data.deviceId,
      success: function (res) {
        wx.hideLoading()
        console.log(that.data.j_id);

        wx.redirectTo({ url: '/hyb_yl/pharmacy/pages/thermometer/index?connectedDeviceId=' + data.deviceId + '&name=' + data.name + '&j_id=' + that.data.j_id + '&type=tem' });
      },
      fail: function (res) {
        wx.hideLoading()
      }
    })
  },
})